$(document).ready(function() {
    // 分页相关变量
    var currentPage = 1;
    var rowsPerPage = 5;
    var allUserData = [];
    var filteredUserData = [];

    // API基础URL - 请根据实际部署情况修改
    const API_BASE_URL = 'http://localhost:5000/api';

    // 当前操作的用户ID
    var currentOperationUserId = null;

    // ==================== 数据获取与渲染 ====================

    // 获取用户列表
    function fetchUsers() {
        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/users`,
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                hideLoading();
                if (response.code === 200) {
                    renderUserTable(response.data);
                    initializeUserData();
                    updateStatistics();
                } else {
                    showError('获取用户列表失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    }

    // 渲染用户表格
    function renderUserTable(users) {
        $('#userTableBody').empty();

        if (users.length === 0) {
            $('#userTableBody').html('<tr><td colspan="12" class="text-center py-4">暂无用户数据</td></tr>');
            return;
        }

        users.forEach((user, index) => {
            const row = `
                <tr>
                    <td class="p-2 border-b">${index + 1}</td>
                    <td class="p-2 border-b">${user.id}</td>
                    <td class="p-2 border-b">${user.password}</td>
                    <td class="p-2 border-b">${user.name}</td>
                    <td class="p-2 border-b">${user.gender}</td>
                    <td class="p-2 border-b">${getRoleText(user.role)}</td>
                    <td class="p-2 border-b">${user.phone}</td>
                    <td class="p-2 border-b">${user.email}</td>
                    <td class="p-2 border-b">${user.address}</td>
                    <td class="p-2 border-b"><span class="user-status user-status-${user.status}">${getStatusText(user.status)}</span></td>
                    <td class="p-2 border-b">${user.registration_time}</td>
                    <td class="p-2 border-b">
                        <button class="btn btn-sm btn-primary-custom" onclick="openUserModal('${user.id}', '${user.name}', '${user.role}', '${user.status}', '${user.registration_time}')">查看详情</button>
                        <button class="btn btn-sm btn-warning bg-yellow-500 text-white p-1 rounded hover:bg-yellow-600" onclick="openEditUserModal('${user.id}')">编辑</button>
                        ${user.status === 'active' ?
                `<button class="btn btn-sm btn-danger bg-red-500 text-white p-1 rounded hover:bg-red-600" onclick="openDeactivateUserModal('${user.id}', '${user.name}')">停用</button>` :
                `<button class="btn btn-sm btn-success bg-green-500 text-white p-1 rounded hover:bg-green-600" onclick="openActivateUserModal('${user.id}', '${user.name}')">启用</button>`
            }
                    </td>
                </tr>
            `;
            $('#userTableBody').append(row);
        });
    }

    // 初始化用户数据
    function initializeUserData() {
        const rows = document.querySelectorAll("#userTableBody tr");
        allUserData = Array.from(rows).map(row => {
            // 标准化角色字段
            let role = row.cells[5].textContent;
            if (role === '普通管理员') role = 'normal_admin';
            if (role === '商城管理员') role = 'mall_admin';
            if (role === '客户') role = 'customer';
            if (role === '卖家') role = 'seller';

            const statusSpan = row.cells[9].querySelector('span');
            const statusText = row.cells[9].querySelector('span').textContent.trim();
            const status = statusText === '活跃' ? 'active' : 'inactive';

            return {
                id: row.cells[1].textContent,
                password: row.cells[2].textContent,
                name: row.cells[3].textContent,
                gender: row.cells[4].textContent,
                role: role,
                phone: row.cells[6].textContent,
                email: row.cells[7].textContent,
                address: row.cells[8].textContent,
                status: status,
                registration_time: row.cells[10].textContent,
                element: row
            };
        });
        filteredUserData = [...allUserData];

        updateTable();
        renderPaginationButtons();
    }

    // ==================== CRUD 操作 ====================

    // 添加用户
    $('#addUserBtn').click(function() {
        const userData = {
            name: $('#addUserName').val(),
            password: $('#addUserPassword').val(),
            gender: $('#addUserGender').val(),
            role: $('#addUserRole').val(),
            phone: $('#addUserPhone').val(),
            email: $('#addUserEmail').val(),
            address: $('#addUserAddress').val(),
            status: $('#addUserStatus').val()
        };

        // 验证必填字段
        if (!validateUserForm(userData)) {
            return;
        }

        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/users`,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(userData),
            success: function(response) {
                hideLoading();
                if (response.code === 201) {
                    showSuccess('用户添加成功');
                    fetchUsers();
                    $('#addUserModal').modal('hide');
                    $('#addUserForm')[0].reset();
                } else {
                    showError('添加失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    });

    // 删除用户
    $('#deleteUserBtn').click(function() {
        if (!confirm(`确定要删除用户 ${currentOperationUserId} 吗？此操作不可撤销！`)) {
            return;
        }

        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/users/${currentOperationUserId}`,
            method: 'DELETE',
            success: function(response) {
                hideLoading();
                if (response.code === 200) {
                    showSuccess('用户删除成功');
                    fetchUsers();
                } else {
                    showError('删除失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    });

    // 编辑用户 - 打开模态框
    function openEditUserModal(userId) {
        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/users/${userId}`,
            method: 'GET',
            success: function(response) {
                hideLoading();
                if (response.code === 200) {
                    const user = response.data;
                    populateEditForm(user);
                    $('#editUserModal').modal('show');
                } else {
                    showError('获取用户详情失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    }

    // 填充编辑表单
    function populateEditForm(user) {
        $('#edit-user-id').val(user.id);
        $('#edit-user-name').val(user.name);
        $('#edit-user-password').val(user.password);
        $('#edit-user-gender').val(user.gender);
        $('#edit-user-role').val(user.role);
        $('#edit-user-phone').val(user.phone);
        $('#edit-user-email').val(user.email);
        $('#edit-user-address').val(user.address);
        $('#edit-user-status').val(user.status);
    }

    // 更新用户
    $('#saveEditUserBtn').click(function() {
        const userId = $('#edit-user-id').val();
        const userData = {
            name: $('#edit-user-name').val(),
            password: $('#edit-user-password').val(),
            gender: $('#edit-user-gender').val(),
            role: $('#edit-user-role').val(),
            phone: $('#edit-user-phone').val(),
            email: $('#edit-user-email').val(),
            address: $('#edit-user-address').val(),
            status: $('#edit-user-status').val()
        };

        // 验证必填字段
        if (!validateUserForm(userData)) {
            return;
        }

        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/users/${userId}`,
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(userData),
            success: function(response) {
                hideLoading();
                if (response.code === 200) {
                    showSuccess('用户更新成功');
                    fetchUsers();
                    $('#editUserModal').modal('hide');
                } else {
                    showError('更新失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    });

    // ==================== 批量操作 ====================

    // 批量导入
    $('#importUsersBtn').click(function() {
        const fileInput = $('#userFileInput')[0];
        const file = fileInput.files[0];

        if (!file) {
            showError('请选择要导入的CSV文件！');
            return;
        }

        const formData = new FormData();
        formData.append('file', file);

        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/users/import`,
            method: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                hideLoading();
                if (response.code === 201) {
                    showSuccess(`成功导入 ${response.data.count} 个用户`);
                    fetchUsers();
                    $('#importUserModal').modal('hide');
                    $('#userFileInput').val('');
                } else {
                    showError('导入失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideError();
                showError('请求失败: ' + error);
            }
        });
    });

    // 数据清理
    $('#cleanUserDataBtn').click(function() {
        if (!confirm('确认要清理所有停用用户数据吗？此操作不可恢复！')) {
            return;
        }

        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/users/clean`,
            method: 'DELETE',
            success: function(response) {
                hideLoading();
                if (response.code === 200) {
                    showSuccess('已清理所有停用用户数据');
                    fetchUsers();
                } else {
                    showError('清理失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    });

    // ==================== 用户状态管理 ====================

    // 停用用户
    function deactivateUser(userId) {
        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/users/${userId}/deactivate`,
            method: 'PUT',
            success: function(response) {
                hideLoading();
                if (response.code === 200) {
                    showSuccess('用户已停用');
                    fetchUsers();
                } else {
                    showError('停用失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    }

    // 启用用户
    function activateUser(userId) {
        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/users/${userId}/activate`,
            method: 'PUT',
            success: function(response) {
                hideLoading();
                if (response.code === 200) {
                    showSuccess('用户已启用');
                    fetchUsers();
                } else {
                    showError('启用失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    }

    // ==================== 辅助函数 ====================

    // 验证用户表单
    function validateUserForm(data) {
        if (!data.name || !data.password || !data.role ||
            !data.phone || !data.email) {
            showError('请填写所有必填字段！');
            return false;
        }

        // 验证邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(data.email)) {
            showError('请输入有效的邮箱地址');
            return false;
        }

        // 验证手机号格式
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(data.phone)) {
            showError('请输入有效的手机号码');
            return false;
        }

        return true;
    }

    // 显示加载状态
    function showLoading() {
        $('#loadingOverlay').removeClass('hidden');
    }

    // 隐藏加载状态
    function hideLoading() {
        $('#loadingOverlay').addClass('hidden');
    }

    // 显示成功消息
    function showSuccess(message) {
        $('#alertSuccess').text(message).removeClass('hidden');
        setTimeout(() => $('#alertSuccess').addClass('hidden'), 3000);
    }

    // 显示错误消息
    function showError(message) {
        $('#alertError').text(message).removeClass('hidden');
        setTimeout(() => $('#alertError').addClass('hidden'), 5000);
    }

    // 获取角色文本
    function getRoleText(role) {
        const roleMap = {
            'customer': '客户',
            'seller': '卖家',
            'normal_admin': '普通管理员',
            'mall_admin': '商城管理员'
        };
        return roleMap[role] || role;
    }

    // 获取状态文本
    function getStatusText(status) {
        const statusMap = {
            'active': '活跃',
            'inactive': '停用'
        };
        return statusMap[status] || status;
    }

    // ==================== 分页与筛选功能 ====================

    // 更新表格显示
    function updateTable() {
        // 隐藏所有行
        allUserData.forEach(user => {
            $(user.element).hide();
        });

        // 显示当前页的行
        const startIndex = (currentPage - 1) * rowsPerPage;
        const endIndex = startIndex + rowsPerPage;
        const usersToShow = filteredUserData.slice(startIndex, endIndex);

        usersToShow.forEach(user => {
            $(user.element).show();
        });

        // 更新分页信息
        updatePaginationInfo();
    }

    // 渲染分页按钮
    function renderPaginationButtons() {
        const totalPages = Math.ceil(filteredUserData.length / rowsPerPage);
        const paginationContainer = $('.pagination-buttons');
        paginationContainer.empty();

        // 最多显示5个页码按钮
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, currentPage + 2);

        if (currentPage <= 3) {
            endPage = Math.min(5, totalPages);
        }
        if (currentPage >= totalPages - 2) {
            startPage = Math.max(1, totalPages - 4);
        }

        // 第一页按钮
        if (startPage > 1) {
            const firstBtn = $('<button>').text('1').addClass('btn btn-page');
            firstBtn.on('click', () => goToPage(1));
            paginationContainer.append(firstBtn);

            if (startPage > 2) {
                paginationContainer.append($('<span>').text('...').addClass('px-2'));
            }
        }

        // 中间页码按钮
        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = $('<button>').text(i).addClass('btn btn-page');
            if (i === currentPage) {
                pageBtn.addClass('bg-blue-500 text-white');
            }
            pageBtn.on('click', () => goToPage(i));
            paginationContainer.append(pageBtn);
        }

        // 最后一页按钮
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                paginationContainer.append($('<span>').text('...').addClass('px-2'));
            }

            const lastBtn = $('<button>').text(totalPages).addClass('btn btn-page');
            lastBtn.on('click', () => goToPage(totalPages));
            paginationContainer.append(lastBtn);
        }
    }

    // 更新分页信息
    function updatePaginationInfo() {
        const totalPages = Math.ceil(filteredUserData.length / rowsPerPage);
        const totalRecords = filteredUserData.length;
        $("#currentPageInfo").text(`当前第 ${currentPage} 页，共 ${totalPages} 页，总计 ${totalRecords} 条记录`);
        renderPaginationButtons();
    }

    // 筛选用户
    function filterUsers() {
        const roleFilter = $('#user-role').val();
        const statusFilter = $('#user-status').val();
        const searchTerm = $('#searchInput').val().toLowerCase();

        filteredUserData = allUserData.filter(user => {
            // 搜索条件
            const matchesSearch = !searchTerm ||
                user.id.toLowerCase().includes(searchTerm) ||
                user.name.toLowerCase().includes(searchTerm) ||
                user.phone.toLowerCase().includes(searchTerm) ||
                user.email.toLowerCase().includes(searchTerm) ||
                user.address.toLowerCase().includes(searchTerm);

            // 角色筛选逻辑
            const roleMatch = roleFilter === 'all' || user.role === roleFilter;

            // 状态筛选逻辑
            const statusMatch = statusFilter === 'all' || user.status === statusFilter;
            return matchesSearch && roleMatch && statusMatch;
        });

        currentPage = 1; // 重置到第一页
        updateTable();
    }

    // 重置筛选
    function resetFilters() {
        $('#user-role').val('all');
        $('#user-status').val('all');
        $('#searchInput').val('');
        filteredUserData = [...allUserData];
        currentPage = 1;
        updateTable();
    }

    // 搜索用户
    function searchUsers() {
        filterUsers();
    }

    // 上一页
    function prevPage() {
        if (currentPage > 1) {
            currentPage--;
            updateTable();
        }
    }

    // 下一页
    function nextPage() {
        const totalPages = Math.ceil(filteredUserData.length / rowsPerPage);
        if (currentPage < totalPages) {
            currentPage++;
            updateTable();
        }
    }

    // 跳转到指定页
    function goToPage(page) {
        const totalPages = Math.ceil(filteredUserData.length / rowsPerPage);
        if (page >= 1 && page <= totalPages) {
            currentPage = page;
            updateTable();
        }
    }

    // ==================== 模态框操作 ====================

    // 打开用户详情模态框
    function openUserModal(userId, userName, userRole, userStatus, registrationTime) {
        $('#user-id').text(userId);
        $('#user-name').text(userName);
        $('#user-role-detail').text(getRoleText(userRole));
        $('#user-status-detail').text(getStatusText(userStatus));
        $('#user-registration-time').text(registrationTime);
        $('#userModal').modal('show');
    }

    // 关闭用户详情模态框
    function closeUserModal() {
        $('#userModal').modal('hide');
    }

    // 打开停用用户确认模态框
    function openDeactivateUserModal(userId, userName) {
        currentOperationUserId = userId;
        $('#deactivate-user-message').text(`您确定要停用用户 ${userName} (ID: ${userId}) 吗？`);
        $('#deactivateUserModal').modal('show');
    }

    // 确认停用用户
    function confirmDeactivateUser() {
        deactivateUser(currentOperationUserId);
        $('#deactivateUserModal').modal('hide');
    }

    // 打开启用用户确认模态框
    function openActivateUserModal(userId, userName) {
        currentOperationUserId = userId;
        $('#activate-user-message').text(`您确定要启用用户 ${userName} (ID: ${userId}) 吗？`);
        $('#activateUserModal').modal('show');
    }

    // 确认启用用户
    function confirmActivateUser() {
        activateUser(currentOperationUserId);
        $('#activateUserModal').modal('hide');
    }

    // ==================== 导出功能 ====================

    // 导出用户数据
    function exportUserData() {
        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/users/export`,
            method: 'GET',
            success: function(response) {
                hideLoading();
                if (response.code === 200) {
                    // 创建一个隐藏的下载链接
                    const link = document.createElement('a');
                    link.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(response.data.csv);
                    link.download = '用户数据.csv';
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    showSuccess('用户数据已导出');
                } else {
                    showError('导出失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    }

    // 生成用户报告
    function generateUserReport() {
        showLoading();
        $.ajax({
            url: `${API_BASE_URL}/users/report`,
            method: 'POST',
            success: function(response) {
                hideLoading();
                if (response.code === 200) {
                    showSuccess('用户报告已生成，已发送到您的邮箱');
                } else {
                    showError('生成报告失败: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showError('请求失败: ' + error);
            }
        });
    }

    // ==================== 初始化页面 ====================

    // 初始化页面时加载数据
    fetchUsers();

    // 绑定筛选按钮事件
    $('.filter-bar .btn-primary-custom').on('click', filterUsers);
    $('.filter-bar .btn-secondary-custom').on('click', resetFilters);

    // 绑定搜索事件
    $('#searchInput').on('input', searchUsers);

    // 绑定高级操作下拉菜单
    $('.dropdown button').on('click', function() {
        $('.dropdown-content').toggleClass('hidden');
    });

    // 关闭下拉菜单当点击其他地方时
    $(document).on('click', function(event) {
        if (!$(event.target).closest('.dropdown').length) {
            $('.dropdown-content').addClass('hidden');
        }
    });
});